package com.fieldchain.ex.fa100.ui.money.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fieldchain.ex.fa100.R;
import com.fieldchain.ex.fa100.access.Constant;
import com.fieldchain.ex.fa100.base.MyBaseActivity;
import com.fieldchain.ex.fa100.bean.AddressBean;
import com.fieldchain.ex.fa100.bean.LvBean;
import com.fieldchain.ex.fa100.bean.User;
import com.fieldchain.ex.fa100.bean.event.CoinEvent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.fieldchain.ex.fa100.utils.common.VerticalUtils;
import com.fieldchain.ex.fa100.utils.net.access.HttpRequest;
import com.fieldchain.ex.fa100.utils.net.common.EmailCode;
import com.fieldchain.ex.fa100.utils.net.common.SmsCode;
import com.fieldchain.ex.fa100.utils.net.modle.BeanRequest;
import com.fieldchain.ex.fa100.utils.net.modle.ImageRequest;
import com.fieldchain.ex.fa100.utils.net.modle.ListRequestTwo;
import com.fieldchain.ex.fa100.utils.net.modle.StringRequest;
import com.fieldchain.ex.fa100.utils.screen.MyToast;
import com.fieldchain.ex.fa100.utils.share.ShareManager;
import com.fieldchain.ex.fa100.utils.string.Arith;
import com.fieldchain.ex.fa100.utils.string.NumberFormate;

/**
 * Created by biyunlong
 * Email: 1225198434@qq.com
 * Data:  2018/10/18
 */
public class WithDrawActivity extends MyBaseActivity implements View.OnClickListener {
    private RelativeLayout reaBack;
    private LinearLayout linTop;
    private TextView tvCompany0;
    private TextView tvRecode;
    private TextView tvNum1;
    private TextView tvCompany1;
    private TextView tvAddress;
    private ImageView ivAddress;
    private EditText etNum1;
    private TextView tvCompany2;
    private TextView tvNum2;
    private TextView tvCompany3;
    private EditText etNum3;
    private EditText etImgcode;
    private ImageView ivImagecode;
    private EditText etSmscode;
    private TextView tvSms;
    private TextView tvNotice;
    private TextView tvNum4;
    private TextView tvCompany4;
    private TextView tvSure;
    private String coin = "";
    private String coinId = "";
    private List<AddressBean> mList = new ArrayList<>();
    private String notice = "提币须知\n确认提币地址为BTC地址，非BTC地址将不可找回。";
    private String address = "";
    private double num;
    private User user;
    private String name = "";
    private boolean isEmail;

    private BigDecimal lv;
    private boolean isRed = false;
    private double sum,max,min;


    @Override
    public void findView() {
        reaBack = findViewById(R.id.rea_back);
        linTop = findViewById(R.id.lin_top);
        tvCompany0 = findViewById(R.id.tv_company0);
        tvRecode = findViewById(R.id.tv_recode);
        tvNum1 = findViewById(R.id.tv_num1);
        tvCompany1 = findViewById(R.id.tv_company1);
        tvAddress = findViewById(R.id.tv_address);
        ivAddress = findViewById(R.id.iv_address);
        etNum1 = findViewById(R.id.et_num1);
        tvCompany2 = findViewById(R.id.tv_company2);
        tvNum2 = findViewById(R.id.tv_num2);
        tvCompany3 = findViewById(R.id.tv_company3);
        etNum3 = findViewById(R.id.et_num3);
        etImgcode = findViewById(R.id.et_imgcode);
        ivImagecode = findViewById(R.id.iv_imagecode);
        etSmscode = findViewById(R.id.et_smscode);
        tvSms = findViewById(R.id.tv_sms);
        tvNotice = findViewById(R.id.tv_notice);
        tvNum4 = findViewById(R.id.tv_num4);
        tvCompany4 = findViewById(R.id.tv_company4);
        tvSure = findViewById(R.id.tv_sure);
    }

    @Override
    public void setValue() {
        coin = getIntent().getStringExtra("coin").toUpperCase();
        coinId = getIntent().getStringExtra("coinId");
        num = getIntent().getDoubleExtra("num", 0.0);
        if (coin != null && coin.length() > 0) {
            notice = notice.replace("BTC", coin);
            setCoin();
        }
        tvNum1.setText(num + "");
        reaBack.setOnClickListener(this);
        tvRecode.setOnClickListener(this);
        linTop.setOnClickListener(this);
        tvSure.setOnClickListener(this);
        ivAddress.setOnClickListener(this);
        ivImagecode.setOnClickListener(this);
        tvSms.setOnClickListener(this);
        getImage();
        getAddress();


        user = ShareManager.getInstance().getUser();
        if (user.getPhone() != null && user.getPhone().length() > 0) {
            name = user.getPhone();
            isEmail = false;
        } else {
            name = user.getEmail();
            isEmail = true;
        }
        getLv();
        initWatcher();
    }

    private void initWatcher() {

        etNum1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence str, int i, int i1, int i2) {
                if (!isRed) {
                    isRed = true;
                    String res = str.toString();

                    if (res.length() > 0) {
                        BigDecimal num = new BigDecimal(res);
                        if ((num.doubleValue() - sum) > 0) {
                            num = new BigDecimal(sum + "");
                            etNum1.setText(sum + "");
                            MyToast.show("余额不足");
                        }
                        if ((num.doubleValue() - max) > 0) {
                            num = new BigDecimal(max + "");
                            etNum1.setText(max + "");
                            MyToast.show("超出最大提币数量："+max);
                        }
                        BigDecimal fee = Arith.mul(num,lv);
                        BigDecimal mc =Arith.sub(num,fee) ;

                        tvNum2.setText(NumberFormate.m5(fee.toPlainString()));
                        tvNum4.setText(NumberFormate.m5(mc.toPlainString()));
                    }
                    isRed = false;
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    public int getLayout() {
        return R.layout.activity_withdraw;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rea_back:
                finish();
                break;
            case R.id.lin_top:
                Intent intent1 = new Intent(mContext, RecChoseActivity.class);
                intent1.putExtra("type", 2);
                startActivity(intent1);
                break;
            case R.id.tv_sure:
                upload();
                break;
            case R.id.tv_recode:
                Intent intent0 = new Intent(mContext, RecListActivity.class);
                intent0.putExtra("coinId", coinId);
                intent0.putExtra("type", 2);
                startActivity(intent0);
                break;
            case R.id.iv_address:
                Intent intent = new Intent(mContext, AddressActivity.class);
                intent.putExtra("coinId", coinId);
                intent.putExtra("address", address);
                startActivity(intent);
                break;
            case R.id.iv_imagecode:
                getImage();
                break;
            case R.id.tv_sms:
                VerticalUtils.getInstance().start(tvSms);
                if (!isEmail) {
                    SmsCode.getInstance().getSms(name, etImgcode.getText().toString());
                } else {
                    EmailCode.getInstance().getEmail(name, etImgcode.getText().toString());
                }
                break;

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void rechargeEvent(CoinEvent et) {
        if (et.getType() == 1) {
            notice = notice.replace(coin, et.getCoin().toUpperCase());
            coin = et.getCoin().toUpperCase();
            coinId = et.getCoinId() + "";
            setCoin();
            getAddress();
            getLv();
            setEmpty();
        } else if (et.getType() == 11) {
            address = et.getCoin();
            String adr;
            if (address.length() > 10) {
                adr = address.substring(0, 5) + "******" + address.substring(address.length() - 5, address.length());
            } else {
                adr = address;
            }
            tvAddress.setText(adr);
        }

    }

    private void setEmpty() {
        etNum1.setText("");
        tvNum2.setText("0.00");
        tvNum4.setText("0.00");

    }


    private void setCoin() {
        tvNotice.setText(notice);
        tvCompany0.setText(coin.toUpperCase());
        tvCompany1.setText(coin.toUpperCase());
        tvCompany2.setText(coin.toUpperCase());
        tvCompany3.setText(coin.toUpperCase());
        tvCompany4.setText(coin.toUpperCase());
    }

    public void getAddress() {
        String url = Constant.getaddress + coinId;
        HashMap map = new HashMap();
        map.put("coinId", coinId);
        HttpRequest.getInstance().getRequest(map, url, new ListRequestTwo<AddressBean>() {
            @Override
            public void onSucess(List<AddressBean> list, int code, String msg) {
                if (code == 200 && list.size() > 0) {
                    address = list.get(0).getWalletAddress();
                    String adr;
                    if (address.length() > 10) {
                        adr = address.substring(0, 5) + "******" + address.substring(address.length() - 5, address.length());
                    } else {
                        adr = address;
                    }
                    tvAddress.setText(adr);
                }
            }

            @Override
            public void onFaild(Exception e) {

            }
        });
    }

    public void getImage() {
        HttpRequest.getInstance().getImage(Constant.image, new ImageRequest() {
            @Override
            public void imgReceive(Bitmap bit) {
                ivImagecode.setImageBitmap(bit);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        VerticalUtils.getInstance().cancle();
    }

    private void upload() {
        String num = etNum1.getText().toString();
        String tpw = etNum3.getText().toString();
        String smsCode = etSmscode.getText().toString();

        if (num.length() == 0) {
            MyToast.show("请输入提币数量");
            return;
        }

        if (tpw.length() == 0) {
            MyToast.show("请输入交易密码");
            return;
        }

        if (smsCode.length() == 0) {
            MyToast.show("请输入验证码");
            return;
        }
        if (address.length() == 0) {
            MyToast.show("请选择提币地址");
            return;
        }

        HashMap map = new HashMap();
        map.put("coinId", coinId);
        map.put("num", num);
        map.put("tpw", tpw);
        map.put("smsCode", smsCode);
        map.put("toAddress", address);

        String url = Constant.addressWithdraw + coinId;
        Log.e("url", url);
        HttpRequest.getInstance().postRequest(map, url, new StringRequest() {
            @Override
            public void onSucess(String str, int code, String msg) {
                if (code == 200) {
                    Intent intent0 = new Intent(mContext, RecListActivity.class);
                    intent0.putExtra("coinId", coinId);
                    intent0.putExtra("type", 2);
                    startActivity(intent0);
                    finish();
                }
                MyToast.show(msg);
            }

            @Override
            public void onFaild(Exception e) {

            }
        });
    }

    public void getLv() {
        HashMap map = new HashMap();
        map.put("id", coinId);
        HttpRequest.getInstance().getRequest(map, Constant.balance, new BeanRequest<LvBean>() {
            @Override
            public void onSucess(LvBean lvBean, int code, String msg) {
                if (code == 200) {
                    lv = new BigDecimal(lvBean.getOutflowFee());
                    lv = lv.divide(new BigDecimal("100.0"), 5, BigDecimal.ROUND_HALF_UP);
                    sum =Double.parseDouble(lvBean.getBalance()+"");
                    tvNum1.setText(lvBean.getBalance() + "");
                    max=lvBean.getOutflowMax();
                    min=lvBean.getOutflowMin();
                    etNum1.setHint("最小提币数量为"+min);
                }
            }

            @Override
            public void onFaild(Exception e) {

            }
        });
    }

}
